﻿/*
The MIT License

Copyright (c) 2009 Gil Beyruth

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

/**
 *Starts new Lobby screen, connects fieldList, userList and 
 *
 */
package com.firstpixel.multiuser
{
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.net.*;
	import flash.utils.getTimer;
	import com.firstpixel.utils.*;
	import com.firstpixel.multiuser.*;
	import fl.controls.ColorPicker;
	import fl.events.ComponentEvent;
	import fl.events.ColorPickerEvent;
	import fl.controls.DataGrid;
	import fl.data.DataProvider;
	com.firstpixel.multiuser.GridRoomEvent;
	import fl.events.ListEvent;
		


	
	public class Lobby extends MovieClip{
		
		//EVENTS
		protected static var disp:EventDispatcher;
		public static function addEventListener(p_type:String, p_listener:Function, p_useCapture:Boolean=false, p_priority:int=0, p_useWeakReference:Boolean=false):void 
		{
			if (disp == null) { disp = new EventDispatcher(); }
			disp.addEventListener(p_type, p_listener, p_useCapture, p_priority, p_useWeakReference);
		}
		public static function removeEventListener(p_type:String, p_listener:Function, p_useCapture:Boolean=false):void 
		{
			if (disp == null) { return; }
			disp.removeEventListener(p_type, p_listener, p_useCapture);
		}
		public static function dispatchEvent(p_event:Event):void
		{
			if (disp == null) { return; }
			disp.dispatchEvent(p_event);
		}
		public static const MISSING_NC:String = "netConnectionMissing"
		
		//vars
		private var dpRoomsCollection:Collection;
		private var dpUsersCollection:Collection;
		private var nc:NetConnection;
		private var userSO:SharedObject=null;
		private var roomSO:SharedObject=null;
		private var chatSO:SharedObject=null;
		private var colorForText:String = "#000000"; 
		public var chatHistory:String = "";
		public var selectedRoom:RoomObj= null;
			
		private var currentChoice:String  = null; 
		
		private var mainTL:MovieClip
		public function Lobby(mtl,serverConnection:ServerConnection=null){
			mainTL = mtl;
			
			trace("NEW LOBBY");
			nc = serverConnection.netConnection;
			userSO=null;
			roomSO=null;
			chatSO=null;
			addEventListener(Event.ADDED_TO_STAGE, addedHandler);
			
			
		}
		private function addedHandler(event:Event):void {
			trace("LOBBY ADDED TO STAGE, READY TO ACCESS MC");
			init(nc);
			MovieClip(mainTL.close_mc).addEventListener(MouseEvent.CLICK,onLogoutLobbyEvent);
			
			addEventListener("histChange",onHistChangeHandler);
			addEventListener("dpUserListChange",onUserListChangeHandler);
			addEventListener("dpUserListReady",onUserListReadyHandler);
			addEventListener("dpRoomListChange",onRoomListChangeHandler);
			addEventListener("dpRoomListReady",onRoomListReadyHandler);
			MovieClip(mainTL).roomGrid_cp.addEventListener(GridRoomEvent.DOUBLE_CLICK, onRoomSelect);
			MovieClip(mainTL).roomGrid_cp.addColumn("Icon");
			MovieClip(mainTL).roomGrid_cp.addColumn("Label");
			MovieClip(mainTL).roomGrid_cp.addColumn("Players");
			
			MovieClip(mainTL).userGrid_cp.addColumn("Username");
			
			MovieClip(mainTL).colorPicker_cp.addEventListener(ColorPickerEvent.CHANGE, colorChangeHandler);
			MovieClip(mainTL).send_bt.enabled = false;  
			MovieClip(mainTL).send_bt.addEventListener(MouseEvent.CLICK, sendMsg);
			MovieClip(mainTL).inputText_cp.addEventListener(Event.CHANGE, onTextEntered);
			

		}
		private function onLogoutLobbyEvent(evt:MouseEvent){
			dispatchEvent(new Event("onLogoutLobbyEvent"));
		}
		private function init(netConnection){
			if(netConnection){
				trace("INIT LOBBY: "+netConnection)
				//userList object
				nc = netConnection;
				
				userSO = SharedObject.getRemote("userSO", nc.uri, false);
				userSO.addEventListener(SyncEvent.SYNC, userSoSync);           		  		
				userSO.addEventListener(NetStatusEvent.NET_STATUS, onSOnetStatus);	            			            		
				userSO.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSOSecurityError);
				userSO.client = this;
				userSO.connect(nc);
				
				initRoomList();
				
				roomSO = SharedObject.getRemote("roomSO", nc.uri, false);
				roomSO.addEventListener(SyncEvent.SYNC, roomSoSync);
				roomSO.addEventListener(NetStatusEvent.NET_STATUS, onSOnetStatus);	            			            		
				roomSO.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSOSecurityError);
				roomSO.client = this;
				roomSO.connect(nc);
				
				chatSO = SharedObject.getRemote("chatSO", nc.uri, false);
				chatSO.addEventListener(NetStatusEvent.NET_STATUS, onSOnetStatus);	            			            		
				chatSO.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSOSecurityError);
				chatSO.client = this;
				chatSO.connect(nc);
			}else{
				onNetConnectionMissing();
			}
			
		}
		private function initRoomList()
		{
			
			dpRoomsCollection = new Collection();
			
			var totalRooms = 10;
			
			for(var i=0;i<totalRooms;i++){
				var roomObj:RoomObj = new RoomObj();		
				roomObj.label = "Stadium "+i;
				roomObj.rtmp = "room_"+i;
				roomObj.rid = i;
				roomObj.userList = "";
				roomObj.icon = "default.jpg";
				roomObj.statustag = "free";
				roomObj.totalClients = 0;
				dpRoomsCollection.addItems(roomObj);
			}
				
		}

		private function onRoomSelect(evt:GridRoomEvent):void
		{
			trace("CLOSE GAME LOBBY"+evt.currentTarget+":"+evt.rid)
			for each (var room:RoomObj in dpRoomsCollection.itemList) {
				trace(room.rid);
				if (room.rid==evt.rid) {
					selectedRoom = room as RoomObj;
					break;
				}
			}
			dispatchEvent(new Event("onCloseLobbyToRoomEvent"));
		}
		private function onTextEntered(evt:Event){
			if(MovieClip(parent).inputText_cp.text != "") {
                MovieClip(parent).send_bt.enabled = true;
				MovieClip(parent).inputText_cp.addEventListener(ComponentEvent.ENTER, sendMsg);
            }
            else {
                MovieClip(parent).send_bt.enabled = false;
				MovieClip(parent).inputText_cp.removeEventListener(ComponentEvent.ENTER, sendMsg);
           
            }

		}
		private function colorChangeHandler(event:ColorPickerEvent):void {
			trace("color changed:"+ event.color+ "(#" + event.target.hexValue + ")");
			colorForText = "#"+event.target.hexValue;
		}

		private function onNetConnectionMissing(){
			dispatchEvent(new Event(MISSING_NC));
		}
		
		
		private function onSOnetStatus(evt:NetStatusEvent):void
		{
		
		}
		private function onSOSecurityError(evt:SecurityErrorEvent):void
		{
		
		}
		
		private function userSoSync(evt:SyncEvent):void
		{
				var results:Object = evt.target.data;				
				dpUsersCollection = new Collection();				
				
				for( var i:String in results )
				{
					trace("USERNAME : "+results[i].username)
					var clientObj:UserObj = new UserObj();		
					clientObj.username = results[i].username;
					clientObj.uid = results[i].uid;
					clientObj.room = results[i].room;
					clientObj.ignore = results[i].ignore;
					clientObj.statustag = results[i].statustag;
					clientObj.type = results[i].type;
					clientObj.talking = results[i].talking;
					clientObj.ip = results[i].ip;
					
					dpUsersCollection.addItems(clientObj);
					dispatchEvent(new Event("dpUserListChange"));
				}
				dispatchEvent(new Event("dpUserListReady"));
		
		}
		
		private function roomSoSync(evt:SyncEvent):void
		{
				var results:Object = evt.target.data;				
				for( var i:String in results )
				{
					var totalClients = 0;
					var usersOn:String = ""				
					for(var j:Object in results[i]){
						trace("RESULT ["+i+" ]["+j+"].username : "+results[i][j].un)
						if(results[i][j].un!=undefined && results[i][j].un!="SERVER")usersOn += results[i][j].un+" "
						if(results[i].length-1>totalClients)usersOn +=",";
						usersOn +=" ";
						totalClients++;
					}
					//this will skip past some enemies that need deleting
					for each (var room:RoomObj in dpRoomsCollection.itemList) { 
						if (room.rtmp==i) {
							trace("UPDATE ROOM : " + i+" userlist: "+usersOn)
							room.userList = usersOn + " ("+totalClients+")";
							room.totalClients = totalClients; 
						}
					}
					dispatchEvent(new Event("dpRoomListChange"));
				}
				
				dispatchEvent(new Event("dpRoomListReady"));
		
		}
		private function onUserListChangeHandler(evt:Event){
			trace("UserListChange")
			
		
		}
		private function onUserListReadyHandler(evt:Event){
			trace("UserListChange")
			var userListDP = new DataProvider(); 
			for each ( var user:UserObj in dpUsersCollection.itemList){
				if(user.ignore==false){
					userListDP.addItem({uid:user.uid,Username:user.username,room:user.room,ip:user.ip})
				}
			}
			MovieClip(mainTL).userGrid_cp.dataProvider = userListDP;
		}
		private function onRoomListChangeHandler(evt:Event){
			trace("RoomListChange")
			
		
		}
		private function onRoomListReadyHandler(evt:Event){
			trace("RoomListChange")
			var roomListDP = new DataProvider(); 
			for each ( var room:RoomObj in dpRoomsCollection.itemList){
				var player = "teste"//room.userList.subCollection(username);
				roomListDP.addItem({rid:room.rid,Label:room.label,Players:room.userList, Total:room.totalClients})
				
			}
			MovieClip(mainTL).roomGrid_cp.dataProvider = roomListDP;
		}
		public function onMsgSend( msg:String ):void
		{
				trace("onMsgSend: " + msg);
				chatHistory += msg;		
				dispatchEvent(new Event("histChange"));
		}
		public function sendMsg(evt:Event):void
		{	
				var msg:String =  MovieClip(parent).inputText_cp.text;
				var outmsg:String = "";			
				outmsg = "<font color='" + colorForText + "'><b>" + Login.username+":</b> " + msg + "</font><br>";
				MovieClip(mainTL).inputText_cp.text = "";
				MovieClip(mainTL).send_bt.enabled = false;
				
				chatSO.send("onMsgSend", outmsg);
		}
		private function onHistChangeHandler(evt:Event){
			MovieClip(mainTL).chat_txt.htmlText = chatHistory;
		}
				
	
	}
}